"""
车辆需求分析模块
用于分析用户需求并返回相应的车辆数据
"""

from .car_data import get_cars_by_price_range, get_cars_by_year, format_car_info

class CarAnalyzer:
    def __init__(self):
        self.price_range = None
        self.year_preference = None
        
    def analyze_requirements(self, ai_response):
        """
        分析AI响应中的用户需求
        :param ai_response: AI的响应文本
        :return: 是否成功识别需求
        """
        # 分析价格区间
        if "5万内" in ai_response:
            self.price_range = (0, 5)
        elif "5-10万" in ai_response:
            self.price_range = (5, 10)
        elif "10万+" in ai_response:
            self.price_range = (10, 30)
        else:
            self.price_range = (0, 30)  # 默认显示所有价格区间的车
            
        # 分析年份偏好
        if "3年内" in ai_response or "准新车" in ai_response:
            self.year_preference = "new"
        elif "5年以上" in ai_response or "高性价比" in ai_response:
            self.year_preference = "old"
        else:
            self.year_preference = None
            
        return True
        
    def get_car_recommendations(self):
        """
        根据分析的需求获取车辆推荐
        :return: 推荐车辆列表
        """
        # 根据价格区间获取车辆
        cars = get_cars_by_price_range(self.price_range[0], self.price_range[1])
        
        # 根据年份偏好筛选
        if self.year_preference == "new":
            cars = get_cars_by_year(2021, True)
        elif self.year_preference == "old":
            cars = get_cars_by_year(2020, False)
            
        return cars
        
    def format_recommendations(self, cars):
        """
        格式化推荐结果
        :param cars: 车辆列表
        :return: 格式化后的推荐信息
        """
        if not cars:
            return "\n\n抱歉，没有找到符合条件的车辆。"
            
        result_message = "\n\n为您找到以下车源：\n"
        for car in cars:
            result_message += format_car_info(car) + "\n"
            
        return result_message
        
    def get_analysis_summary(self):
        """
        获取需求分析摘要
        :return: 分析摘要字典
        """
        return {
            "price_range": self.price_range,
            "year_preference": self.year_preference,
            "price_range_text": self._get_price_range_text(),
            "year_preference_text": self._get_year_preference_text()
        }
        
    def _get_price_range_text(self):
        """获取价格区间文本描述"""
        if self.price_range[1] <= 5:
            return "5万内"
        elif self.price_range[1] <= 10:
            return "5-10万"
        else:
            return "10万以上"
            
    def _get_year_preference_text(self):
        """获取年份偏好文本描述"""
        if self.year_preference == "new":
            return "3年内准新车"
        elif self.year_preference == "old":
            return "5年以上高性价比"
        else:
            return "不限年份" 